package com.jpcc.vw.onlineRadio.service;

import android.content.Context;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.EventLog;

import com.cns.android.media.MediaInfoManager;
import com.google.android.exoplayer2.ext.mediaplayer.ExoMediaPlayer;
import com.google.android.exoplayer2.ext.mediaplayer.MediaPlayerInterface;
import com.google.gson.Gson;
import com.jpcc.vw.onlineRadio.R;
import com.jpcc.vw.onlineRadio.application.MusicApplication;
import com.jpcc.vw.onlineRadio.constants.Constants;
import com.jpcc.vw.onlineRadio.model.action.RadioCountAction;
import com.jpcc.vw.onlineRadio.model.action.WaveAction;
import com.jpcc.vw.onlineRadio.model.bean.RecentAlbumRadioTrackBean;
import com.jpcc.vw.onlineRadio.model.bean.Track;
import com.jpcc.vw.onlineRadio.utils.PreferenceUtils;
import com.jpcc.vw.onlineRadio.utils.ToastUtils;
import com.jpcc.vw.onlineRadio.utils.Track2RecentAlbumTrackUtils;
import com.orhanobut.logger.Logger;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;

import static android.content.Context.AUDIO_SERVICE;


/**
 * Created by hzwangchenyan on 2018/1/26.
 */
public class AlbumRadioAudioPlayer {
    private static final int STATE_IDLE = 0;
    private static final int STATE_PREPARING = 1;
    private static final int STATE_PLAYING = 2;
    private static final int STATE_PAUSE = 3;

    private static final long TIME_UPDATE = 1000L;

    private Context context;
    private AudioFocusManager audioFocusManager;
    private ExoMediaPlayer mediaPlayer;
    private Handler handler;
    //    private NoisyAudioStreamReceiver noisyReceiver;
    private IntentFilter noisyFilter;
    //    private List<Music> musicList;
    private RecentAlbumRadioTrackBean source;
    private List<Track> tracks = new ArrayList<>();
    private final List<OnAlbumRadioPlayerEventListener> listeners = new ArrayList<>();
    private int state = STATE_IDLE;
    private int currentDuration = 0;
    private int radioPosition = 0;
    private String playUrlForPaied = "";

    public static AlbumRadioAudioPlayer get() {
        return SingletonHolder.instance;
    }

    private static class SingletonHolder {
        private static AlbumRadioAudioPlayer instance = new AlbumRadioAudioPlayer();
    }

    private AlbumRadioAudioPlayer() {
    }


    public AudioFocusManager getAudioFocusManager() {
        return audioFocusManager;
    }

    public void init(Context context) {
        this.context = context.getApplicationContext();
//        musicList = DBManager.get().getMusicDao().queryBuilder().build().list();
        prepareInitData();
        Logger.i("playing_status-->" + PreferenceUtils.GetRadioPlayingStatus());
        audioFocusManager = new AudioFocusManager(context);
        mediaPlayer = new ExoMediaPlayer(MusicApplication.GetInstance());
//        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        handler = new Handler(Looper.getMainLooper());
//        noisyReceiver = new NoisyAudioStreamReceiver();
        noisyFilter = new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
//        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
//            @Override
//            public void onCompletion(MediaPlayer mp) {
//                if (source != null) {
//                    next();
//                    for (OnAlbumRadioPlayerEventListener listener : listeners) {
//                        listener.onFinishTrack();
//                    }
//                    RadioCountAction action=new RadioCountAction();
//                    action.setEvent("end");
//                    action.setModuleId("radio");
//                    action.setPreserved(false);
//                    action.setStation(source.getAlbumName());
//                    action.setStationId(source.getAlbumId()+"");
//                    EventBus.getDefault().post(action);
//                }
//            }
//        });


        mediaPlayer.setOnCompletionListener(new MediaPlayerInterface.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayerInterface mp) {
                playUrlForPaied = "";
                if (source != null) {
                    if (source.isLive()) {
                        return;
                    }
                    next();
                    for (OnAlbumRadioPlayerEventListener listener : listeners) {


                        Observable.just("action").observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
                            @Override
                            public void onCompleted() {

                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onNext(String s) {
                                listener.onFinishTrack();
                            }
                        });


                    }
                    RadioCountAction action = new RadioCountAction();
                    action.setEvent("end");
                    action.setModuleId("radio");
                    action.setPreserved(false);
                    action.setStation(source.getAlbumName());
                    action.setStationId(source.getAlbumId() + "");
                    EventBus.getDefault().post(action);
                }
            }
        });

//        mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
//            @Override
//            public boolean onError(MediaPlayer mp, int what, int extra) {
//                return false;
//            }
//        });


        mediaPlayer.setOnErrorListener(new MediaPlayerInterface.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayerInterface mp, int what, int extra) {
                Logger.i("onError-->error occured");
                if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                    playPause();
//                    Constants.FLAG_FOCUS_ON_SELF=false;
//                    pausePlayerTemporary();
//                    PreferenceUtils.SaveAudioFocusStatus(false);
//                    Logger.i("onAudioFocusChange-->AUDIOFOCUS_LOSS");
//                    Logger.i("isPlaying()-->"+isPlaying());
//                    Logger.i("FLAG_PAUSE_MANUAL-->"+Constants.FLAG_PAUSE_MANUAL);
                } else if (mediaPlayer != null) {
                    if (state == STATE_IDLE || state == STATE_PREPARING || state == STATE_PLAYING) {
                        pausePlayer();
                    }
                }
                return false;
            }
        });

        mediaPlayer.setOnPreparedListener(new MediaPlayerInterface.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayerInterface mp) {
                if (isPreparing()) {
                    if (source != null) {
                        startPlayer();
                        mediaPlayer.seekTo(currentDuration);
                        currentDuration = currentDuration;


                        RadioCountAction action = new RadioCountAction();
                        action.setEvent("listen");
                        action.setModuleId("radio");
                        action.setPreserved(false);
                        action.setStation(source.getAlbumName());
                        action.setStationId(source.getAlbumId() + "");
                        EventBus.getDefault().post(action);
                    }
                }
            }
        });
//        mediaPlayer.setOnBufferingUpdateListener((mp, percent) -> {
//            for (OnAlbumRadioPlayerEventListener listener : listeners) {
//
//
//                Observable.just("action").observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
//                    @Override
//                    public void onCompleted() {
//
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//
//                    }
//
//                    @Override
//                    public void onNext(String s) {
//                        listener.onBufferingUpdate(percent);
//                    }
//                });
//
//
//            }
//        });
    }

    private void prepareInitData() {
//        DatabaseHelperOrm helper = DatabaseHelperOrm.getHelper(context);
//        HashMap<String, Object> queryMaps = new HashMap<>();
//        queryMaps.put("userId", MusicApplication.GetUserId());
//        try {
//            List<RecentAlbumRadioTrackBean> datas = helper.getRecentDao().queryBuilder().orderBy("timeStamp", false).where().eq("userId",MusicApplication.GetUserId()).query();
//            if (datas != null && datas.size() > 0) {
//                source = datas.get(0);
//            }
//        } catch (SQLException e) {
//            e.printStackTrace();
//        }


//        source = new RecentAlbumRadioTrackBean();
//        source.setUserId(MusicApplication.GetUserId());
//        source.setType("radio");
//        source.setAlbumId(12345678);
//        source.setAlbumName("怪咖");
//        source.setAuthor("薛之谦");
//        source.setTrackId(59785418);
//        source.setFrom(0);
//        source.setLive(false);
//        source.setTrackPageIndex(1);
//        source.setCover("http://qukufile2.qianqian.com/data2/pic/97ddb0b1228765f1b23194d45305be54/599300699/599300699.jpg@s_1,w_150,h_150");
//        source.setTrackUrl("http://zhangmenshiting.qianqian.com/data2/music/0bf349baa6b5cc2b0fc8a22aba62f891/599300735/599300735.mp3?xcode=066ec92133816d5537ff48ca31f559c2");
//        source.setDuration(267000);
//        source.setTimeStamp(new Date().getTime());
    }

    public void addOnPlayEventListener(OnAlbumRadioPlayerEventListener listener) {
        if (!listeners.contains(listener)) {
            listeners.add(listener);
        }
    }

    public void removeOnPlayEventListener(OnAlbumRadioPlayerEventListener listener) {
        listeners.remove(listener);
    }

    public void addAndPlay(RecentAlbumRadioTrackBean entity) {
//        int position = musicList.indexOf(music);
//        if (position < 0) {
//            musicList.add(music);
//            DBManager.get().getMusicDao().insert(music);
//            position = musicList.size() - 1;
//        }
        source = entity;
        play();
    }


    public List<Track> getPlayerList() {
        return tracks;
    }


    public void setOnSources(List<Track> infos, int position, int from, int duration) {
        setUnmute();
        Logger.i("setOnSources-->" + infos.toString() + ", " + position + ", " + from);
        PreferenceUtils.SaveLastJson(new Gson().toJson(infos));
        Logger.i("setOnSources-->" + PreferenceUtils.GetLastPlayingJson());
        //保护性代码
        if (position >= infos.size()) {
            return;
        }
        tracks = new ArrayList<>();
        tracks.addAll(infos);
        PreferenceUtils.SaveLastJson(new Gson().toJson(tracks));
        source = Track2RecentAlbumTrackUtils.Track2RecentBean(infos.get(position));
        radioPosition = position;
        source.setFrom(from);
        if (!source.isIs_paid()) {
            play();
        } else {
            playForPaiedAlbum();
        }
        if (duration != -1) {
            currentDuration = duration;
        } else {
            currentDuration = 0;
        }
    }


    public void setOnSourcesForRadio(List<Track> listenbackList, Track liveTrack, boolean isLive, int position) {
        setUnmute();
        tracks = new ArrayList<>();
        tracks.addAll(listenbackList);
        PreferenceUtils.SaveLastJson(new Gson().toJson(listenbackList));
        tracks.add(liveTrack);
        PreferenceUtils.SaveLastJson(new Gson().toJson(tracks));
        if (isLive) {
            source = Track2RecentAlbumTrackUtils.Track2RecentBeanListenback(liveTrack);
            radioPosition = tracks.size();
        } else {
            Track localTrack = listenbackList.get(position);
            source = Track2RecentAlbumTrackUtils.Track2RecentBeanListenback(localTrack);
            radioPosition = position;
        }
        source.setFrom(4);
        play();
        currentDuration = 0;
    }


    public void setOnSourcesForListenbackRadio(List<Track> infos, int position, int from) {
        setUnmute();
        tracks = new ArrayList<>();
        tracks.addAll(infos);
        PreferenceUtils.SaveLastJson(new Gson().toJson(tracks));
        source = Track2RecentAlbumTrackUtils.Track2RecentBeanListenback(infos.get(position));
        radioPosition = position;
//        source.setLive(false);
        source.setFrom(from);
        play();
    }


    public List<Track> getTracks() {
        List<Track> infos = new ArrayList<>();
        infos.addAll(tracks);
        return infos;
    }

    public void play() {
        if (source == null) {
            return;
        }
        Logger.i("radio play()");
        try {
            if (mediaPlayer != null) {
                mediaPlayer.release();
            }
            mediaPlayer = new ExoMediaPlayer(MusicApplication.GetInstance());


            mediaPlayer.setOnCompletionListener(new MediaPlayerInterface.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayerInterface mp) {
                    playUrlForPaied = "";
                    if (source != null) {
                        if (source.isLive()) {
                            return;
                        }
                        next();
                        for (OnAlbumRadioPlayerEventListener listener : listeners) {


                            Observable.just("action").observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
                                @Override
                                public void onCompleted() {

                                }

                                @Override
                                public void onError(Throwable e) {

                                }

                                @Override
                                public void onNext(String s) {
                                    listener.onFinishTrack();
                                }
                            });


                        }
                        RadioCountAction action = new RadioCountAction();
                        action.setEvent("end");
                        action.setModuleId("radio");
                        action.setPreserved(false);
                        action.setStation(source.getAlbumName());
                        action.setStationId(source.getAlbumId() + "");
                        EventBus.getDefault().post(action);
                    }
                }
            });
            mediaPlayer.setOnPreparedListener(new MediaPlayerInterface.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayerInterface mp) {
                    if (isPreparing()) {
                        if (source != null) {
                            startPlayer();
                            mediaPlayer.seekTo(currentDuration);
//                            currentDuration = currentDuration;
                            RadioCountAction action = new RadioCountAction();
                            action.setEvent("listen");
                            action.setModuleId("radio");
                            action.setPreserved(false);
                            action.setStation(source.getAlbumName());
                            action.setStationId(source.getAlbumId() + "");
                            EventBus.getDefault().post(action);
                        }
                    }
                }
            });
            mediaPlayer.setOnErrorListener(new MediaPlayerInterface.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayerInterface mp, int what, int extra) {
//                    ToastUtils.show(R.string.string_55);


//                    setOnSources(getTracks(),radioPosition,source.getFrom(),-1);


                    if (false) {
                        try {
                            MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendTileStatus(MediaInfoManager.TILE_STATUS_UNAVAILABLE, "data error");
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                    }


                    if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                        playPause();
//                        Constants.FLAG_FOCUS_ON_SELF=false;
//                        pausePlayerTemporary();
//                        PreferenceUtils.SaveAudioFocusStatus(false);
//                        Logger.i("onAudioFocusChange-->AUDIOFOCUS_LOSS");
//                        Logger.i("isPlaying()-->"+isPlaying());
//                        Logger.i("FLAG_PAUSE_MANUAL-->"+Constants.FLAG_PAUSE_MANUAL);
                    } else if (mediaPlayer != null) {
                        if (state == STATE_IDLE || state == STATE_PREPARING || state == STATE_PLAYING) {
                            pausePlayer();
                        }
                    }

                    return false;
                }
            });
            if (TextUtils.isEmpty(source.getTrackUrl())) {
                if (source.isIs_paid() && !source.isIs_authorized()) {
                    for (OnAlbumRadioPlayerEventListener listener : listeners) {
                        Observable.just("action").observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
                            @Override
                            public void onCompleted() {

                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onNext(String s) {
                                listener.onToPayAlumTrack(source);
                            }
                        });
                    }
                } else {
                    ToastUtils.show(R.string.string_65);
                }
            } else {
                if ("album".equals(source.getType())) {
                    if (source.getFrom() == 1) {
                        mediaPlayer.setDataSource(source.getTrackUrl());
                        if (Constants.isRelease) {
                            try {
                                MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendFocusedMediaPackageName("com.jpcc.vw.onlineRadio");
                                MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendTileStatus(MediaInfoManager.TILE_STATUS_AVAILABLE, "");
                            } catch (RemoteException e) {
                                e.printStackTrace();
                            }
                        }
                    } else {
                        if ((source.getTrackUrl() == null) || (TextUtils.isEmpty(source.getTrackUrl().trim()))) {
                            ToastUtils.show(R.string.string_65);
                            if (Constants.isRelease) {
                                try {
                                    MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendFocusedMediaPackageName("com.jpcc.vw.onlineRadio");
                                    MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendTileStatus(MediaInfoManager.TILE_STATUS_UNAVAILABLE, "data error");
                                } catch (RemoteException e) {
                                    e.printStackTrace();
                                }
                            }
                            mediaPlayer.setDataSource("");
                        } else {
                            String proxyUrl = MusicApplication.getProxy(MusicApplication.GetInstance()).getProxyUrl(source.getTrackUrl());
                            Logger.i("proxyUrl-->" + proxyUrl);
                            mediaPlayer.setDataSource(proxyUrl);
                            if (Constants.isRelease) {
                                try {
                                    MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendFocusedMediaPackageName("com.jpcc.vw.onlineRadio");
                                    MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendTileStatus(MediaInfoManager.TILE_STATUS_AVAILABLE, "");
                                } catch (RemoteException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                    mediaPlayer.setOnBufferingUpdateListener(new MediaPlayerInterface.OnBufferingUpdateListener() {
                        @Override
                        public void onBufferingUpdate(MediaPlayerInterface mp, int percent) {
//                        Logger.i("onBufferingUpdate-->" + percent);
                            for (OnAlbumRadioPlayerEventListener listener : listeners) {
                                Observable.just("action").observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
                                    @Override
                                    public void onCompleted() {

                                    }

                                    @Override
                                    public void onError(Throwable e) {

                                    }

                                    @Override
                                    public void onNext(String s) {
                                        if ("album".equals(source.getType())) {
                                            listener.onBufferingUpdate(percent);
                                        } else {
                                            listener.onBufferingUpdate(0);
                                        }
                                    }
                                });
                            }
                        }
                    });
                } else {
                    if ((source.getTrackUrl() == null) || (TextUtils.isEmpty(source.getTrackUrl().trim()))) {
                        ToastUtils.show(R.string.string_65);
                        if (Constants.isRelease) {
                            try {
                                MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendTileStatus(MediaInfoManager.TILE_STATUS_UNAVAILABLE, "data error");
                            } catch (RemoteException e) {
                                e.printStackTrace();
                            }
                        }
                    } else {
                        if (Constants.isRelease) {
                            try {
                                MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendTileStatus(MediaInfoManager.TILE_STATUS_AVAILABLE, "");
                            } catch (RemoteException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    mediaPlayer.setDataSource(source.getTrackUrl());
                    mediaPlayer.setOnBufferingUpdateListener(new MediaPlayerInterface.OnBufferingUpdateListener() {
                        @Override
                        public void onBufferingUpdate(MediaPlayerInterface mp, int percent) {
                            for (OnAlbumRadioPlayerEventListener listener : listeners) {
                                Observable.just("action").observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
                                    @Override
                                    public void onCompleted() {

                                    }

                                    @Override
                                    public void onError(Throwable e) {

                                    }

                                    @Override
                                    public void onNext(String s) {
                                        if ("album".equals(source.getType())) {
                                            listener.onBufferingUpdate(percent);
                                        } else {
                                            listener.onBufferingUpdate(0);
                                        }
                                    }
                                });
                            }
                        }
                    });
                }


                mediaPlayer.prepareAsync();
                state = STATE_PREPARING;
                EventBus.getDefault().post(new WaveAction());
                for (OnAlbumRadioPlayerEventListener listener : listeners) {


                    Observable.just("action").observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onNext(String s) {
                            listener.onChange(source);
                        }
                    });


                }
//            Notifier.get().showPlay(music);
                AlbumMediaSessionManager.get().updateMetaData(source);
                AlbumMediaSessionManager.get().updatePlaybackState();
                if ("album".equals(source.getType())) {
//                DatabaseHelperOrm helper = DatabaseHelperOrm.getHelper(context);
//                HashMap<String, Object> queryMaps = new HashMap<>();
//                queryMaps.put("userId", MusicApplication.GetUserId());
//                queryMaps.put("toUserId", to_user_id);
//                seekTo();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            ToastUtils.show(R.string.string_38);
        }
    }


    public void setPlayUrl(String playUrl) {
        this.playUrlForPaied = playUrl;
        if (mediaPlayer != null) {
            mediaPlayer.release();
        }
        mediaPlayer = new ExoMediaPlayer(MusicApplication.GetInstance());
        mediaPlayer.setOnCompletionListener(new MediaPlayerInterface.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayerInterface mp) {
                playUrlForPaied = "";
                if (source != null) {
                    if (source.isLive()) {
                        return;
                    }
                    next();
                    for (OnAlbumRadioPlayerEventListener listener : listeners) {
                        Observable.just("action").observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
                            @Override
                            public void onCompleted() {

                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onNext(String s) {
                                listener.onFinishTrack();
                            }
                        });
                    }
                    RadioCountAction action = new RadioCountAction();
                    action.setEvent("end");
                    action.setModuleId("radio");
                    action.setPreserved(false);
                    action.setStation(source.getAlbumName());
                    action.setStationId(source.getAlbumId() + "");
                    EventBus.getDefault().post(action);
                }
            }
        });
        mediaPlayer.setOnPreparedListener(new MediaPlayerInterface.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayerInterface mp) {
                if (isPreparing()) {
                    if (source != null) {
                        startPlayer();
                        currentDuration = currentDuration;
                        RadioCountAction action = new RadioCountAction();
                        action.setEvent("listen");
                        action.setModuleId("radio");
                        action.setPreserved(false);
                        action.setStation(source.getAlbumName());
                        action.setStationId(source.getAlbumId() + "");
                        EventBus.getDefault().post(action);
                    }
                }
            }
        });
        mediaPlayer.setOnErrorListener(new MediaPlayerInterface.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayerInterface mp, int what, int extra) {
//                    ToastUtils.show(R.string.string_55);
//                next();
                if (false) {
                    try {
                        MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendTileStatus(MediaInfoManager.TILE_STATUS_UNAVAILABLE, "data error");
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }


                if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                    playPause();
//                    Constants.FLAG_FOCUS_ON_SELF=false;
//                    pausePlayerTemporary();
//                    PreferenceUtils.SaveAudioFocusStatus(false);
//                    Logger.i("onAudioFocusChange-->AUDIOFOCUS_LOSS");
//                    Logger.i("isPlaying()-->"+isPlaying());
//                    Logger.i("FLAG_PAUSE_MANUAL-->"+Constants.FLAG_PAUSE_MANUAL);
                } else if (mediaPlayer != null) {
                    if (state == STATE_IDLE || state == STATE_PREPARING || state == STATE_PLAYING) {
                        pausePlayer();
                    }
                }

                return false;
            }
        });
        mediaPlayer.setOnBufferingUpdateListener(new MediaPlayerInterface.OnBufferingUpdateListener() {
            @Override
            public void onBufferingUpdate(MediaPlayerInterface mp, int percent) {
//                        Logger.i("onBufferingUpdate-->" + percent);
                for (OnAlbumRadioPlayerEventListener listener : listeners) {
                    Observable.just("action").observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onNext(String s) {
                            if ("album".equals(source.getType())) {
                                listener.onBufferingUpdate(percent);
                            } else {
                                listener.onBufferingUpdate(0);
                            }
                        }
                    });
                }
            }
        });

        try {
            mediaPlayer.setDataSource(this.playUrlForPaied);
            mediaPlayer.prepareAsync();
            state = STATE_PREPARING;
            EventBus.getDefault().post(new WaveAction());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public void playForPaiedAlbum() {
        if (source == null) {
            return;
        }
        if (false) {
        } else {

            if (source == null) {
                return;
            }
            Logger.i("radio play()");

            if (mediaPlayer != null) {
                mediaPlayer.release();
            }
            mediaPlayer = new ExoMediaPlayer(MusicApplication.GetInstance());


            mediaPlayer.setOnCompletionListener(new MediaPlayerInterface.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayerInterface mp) {
                    playUrlForPaied = "";
                    if (source != null) {
                        if (source.isLive()) {
                            return;
                        }
                        next();
                        for (OnAlbumRadioPlayerEventListener listener : listeners) {


                            Observable.just("action").observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
                                @Override
                                public void onCompleted() {

                                }

                                @Override
                                public void onError(Throwable e) {

                                }

                                @Override
                                public void onNext(String s) {
                                    listener.onFinishTrack();
                                }
                            });


                        }
                        RadioCountAction action = new RadioCountAction();
                        action.setEvent("end");
                        action.setModuleId("radio");
                        action.setPreserved(false);
                        action.setStation(source.getAlbumName());
                        action.setStationId(source.getAlbumId() + "");
                        EventBus.getDefault().post(action);
                    }
                }
            });


            mediaPlayer.setOnPreparedListener(new MediaPlayerInterface.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayerInterface mp) {
                    if (isPreparing()) {
                        if (source != null) {
                            startPlayer();
                            mediaPlayer.seekTo(currentDuration);
                            currentDuration = currentDuration;
                            RadioCountAction action = new RadioCountAction();
                            action.setEvent("listen");
                            action.setModuleId("radio");
                            action.setPreserved(false);
                            action.setStation(source.getAlbumName());
                            action.setStationId(source.getAlbumId() + "");
                            EventBus.getDefault().post(action);
                        }
                    }
                }
            });


            mediaPlayer.setOnErrorListener(new MediaPlayerInterface.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayerInterface mp, int what, int extra) {
//                    ToastUtils.show(R.string.string_55);
//                    next();
                    if (false) {
                        try {
                            MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendTileStatus(MediaInfoManager.TILE_STATUS_UNAVAILABLE, "data error");
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                    }


                    if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                        playPause();
//                        Constants.FLAG_FOCUS_ON_SELF=false;
//                        pausePlayerTemporary();
//                        PreferenceUtils.SaveAudioFocusStatus(false);
//                        Logger.i("onAudioFocusChange-->AUDIOFOCUS_LOSS");
//                        Logger.i("isPlaying()-->"+isPlaying());
//                        Logger.i("FLAG_PAUSE_MANUAL-->"+Constants.FLAG_PAUSE_MANUAL);
                    } else if (mediaPlayer != null) {
                        if (state == STATE_IDLE || state == STATE_PREPARING || state == STATE_PLAYING) {
                            pausePlayer();
                        }
                    }

                    return false;
                }
            });


            mediaPlayer.prepareAsync();
            state = STATE_PREPARING;
            EventBus.getDefault().post(new WaveAction());
            for (OnAlbumRadioPlayerEventListener listener : listeners) {
                Observable.just("action").observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(String s) {
                        listener.onChange(source);
                    }
                });
            }
            AlbumMediaSessionManager.get().updateMetaData(source);
            AlbumMediaSessionManager.get().updatePlaybackState();
            if ("album".equals(source.getType())) {
                if (!source.isVipFree()) {
                    if ((source.isIs_paid() && source.isIs_authorized()) || (source.isIs_paid() && source.isIs_free())) {
                        //获取播放地址就行了
                        for (OnAlbumRadioPlayerEventListener listener : listeners) {
                            Observable.just("action").observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
                                @Override
                                public void onCompleted() {

                                }

                                @Override
                                public void onError(Throwable e) {

                                }

                                @Override
                                public void onNext(String s) {
                                    listener.onGetPlayInfo(source.getTrackId());
                                }
                            });
                        }
                    } else {
                        //弹出付费画面进行付费
                        for (OnAlbumRadioPlayerEventListener listener : listeners) {
                            Observable.just("action").observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
                                @Override
                                public void onCompleted() {

                                }

                                @Override
                                public void onError(Throwable e) {

                                }

                                @Override
                                public void onNext(String s) {
                                    listener.onGetPayDialog(source.getAlbumId(), source.getTrackId());
                                }
                            });
                        }
                    }
                } else {
                    //可以免费试听的Track
                    if (source.isIs_free()) {
                        for (OnAlbumRadioPlayerEventListener listener : listeners) {
                            Observable.just("action").observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
                                @Override
                                public void onCompleted() {

                                }

                                @Override
                                public void onError(Throwable e) {

                                }

                                @Override
                                public void onNext(String s) {
                                    //获取播放地址
                                    listener.onGetPlayInfo(source.getTrackId());
                                }
                            });
                        }
                    } else {
                        if (PreferenceUtils.GetVIPStatus()) {
                            for (OnAlbumRadioPlayerEventListener listener : listeners) {
                                Observable.just("action").observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
                                    @Override
                                    public void onCompleted() {

                                    }

                                    @Override
                                    public void onError(Throwable e) {

                                    }

                                    @Override
                                    public void onNext(String s) {
                                        //获取播放地址
                                        listener.onGetPlayInfo(source.getTrackId());
                                    }
                                });
                            }
                        } else {
                            for (OnAlbumRadioPlayerEventListener listener : listeners) {
                                Observable.just("action").observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
                                    @Override
                                    public void onCompleted() {

                                    }

                                    @Override
                                    public void onError(Throwable e) {

                                    }

                                    @Override
                                    public void onNext(String s) {
                                        //获取播放地址
                                        listener.onGetVIPDialog();
                                    }
                                });
                            }
                        }
                    }
                }
            }
        }
//        } catch (Exception e) {
//            e.printStackTrace();
//            ToastUtils.show(R.string.string_38);
//        }
    }

    public void delete() {
    }

    public void playPauseTemporary() {
        Logger.i("radio enter player playPause");
        if (isPreparing()) {
            stopPlayer();
        } else if (isPlaying()) {
            pausePlayerTemporary();
        } else if (isPausing()) {
            startPlayer();
        } else {
            play();
        }
    }

    public void pausePlayerTemporary() {
        if (!isPlaying()) {
            return;
        }
        Logger.i("radio pausePlayer()");
        mediaPlayer.pause();
//        PreferenceUtils.SaveRadioPlayingStatus(false);
        state = STATE_PAUSE;
        EventBus.getDefault().post(new WaveAction());
        handler.removeCallbacks(mPublishRunnable);
//        Notifier.get().showPause(getPlayMusic());
        AlbumMediaSessionManager.get().updatePlaybackState();
//        context.unregisterReceiver(noisyReceiver);
//        Constants.FLAG_PAUSE_MANUAL = abandonAudioFocus;
//        if (abandonAudioFocus) {
////            audioFocusManager.abandonAudioFocus();
//            PreferenceUtils.SaveAudioFocusStatus(false);
//        }
//        PreferenceUtils.SaveRadioPlayingStatus(false);
        for (OnAlbumRadioPlayerEventListener listener : listeners) {


            Observable.just("action").observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onNext(String s) {
                    listener.onPlayerPause();
                }
            });


        }
    }

    public void playPause() {
        Logger.i("radio enter player playPause");
        if (isPreparing()) {
            stopPlayer();
//            EventBus.getDefault().post(new WaveAction());
        } else if (isPlaying()) {
            pausePlayer();
//            EventBus.getDefault().post(new WaveAction());
        } else if (isPausing()) {
            startPlayer();
//            EventBus.getDefault().post(new WaveAction());
        } else {
            play();
//            EventBus.getDefault().post(new WaveAction());
        }
    }


    public void playPauseAbandonFocus() {
        Logger.i("radio enter player playPause");
        if (isPreparing()) {
            stopPlayer();
//            EventBus.getDefault().post(new WaveAction());
        } else if (isPlaying()) {
            audioFocusManager.getAudioFocusManager().setParameters("jpcc.music=mute");
            pausePlayer(true);
//            EventBus.getDefault().post(new WaveAction());
        } else if (isPausing()) {
//            ((AudioManager) context.getSystemService(AUDIO_SERVICE)).setParameters("jpcc.music=unmute");
            audioFocusManager.getAudioFocusManager().setParameters("jpcc.music=unmute");
            startPlayer();
//            EventBus.getDefault().post(new WaveAction());
        } else {
//            ((AudioManager) context.getSystemService(AUDIO_SERVICE)).setParameters("jpcc.music=unmute");
            audioFocusManager.getAudioFocusManager().setParameters("jpcc.music=unmute");
            startPlayer();
//            EventBus.getDefault().post(new WaveAction());
        }
    }

    public void startPlayer() {
        if (!isPreparing() && !isPausing()) {
            return;
        }
        if (source == null) {
            return;
        }
        Logger.i("startPlayer()--->startPlayer()");
        if (audioFocusManager == null) {
            Logger.i("startPlayer()--->audioFocusManager is null");
            return;
        }
        if (audioFocusManager.requestAudioFocus()) {
            Logger.i("startPlayer()--->requestedAudioFocus");
            try {
                MediaInfoManager.getInstance(MusicApplication.GetInstance()).sendFocusedMediaPackageName("com.jpcc.vw.onlineRadio");
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            PreferenceUtils.SaveAudioFocusStatus(true);

            Logger.i("LastMode-->" + Constants.LastModeFlag);
            Logger.i("RadioPlayingStatus-->" + PreferenceUtils.GetRadioPlayingStatus());
            if (Constants.LastModeFlag) {
                if (PreferenceUtils.GetRadioPlayingStatus()) {
                    Constants.LastModeFlag = false;
                    state = STATE_PLAYING;
                    EventBus.getDefault().post(new WaveAction());
                    handler.post(mPublishRunnable);
                    AlbumMediaSessionManager.get().updatePlaybackState();
                    mediaPlayer.start();
                    PreferenceUtils.SaveRadioPlayingStatus(true);
                    for (OnAlbumRadioPlayerEventListener listener : listeners) {
                        Observable.just("action").observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
                            @Override
                            public void onCompleted() {

                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onNext(String s) {
                                listener.onPlayerStart();
                            }
                        });
                    }
                } else {
                    mediaPlayer.start();
                    state = STATE_PAUSE;
                    EventBus.getDefault().post(new WaveAction());
//                    handler.post(mPublishRunnable);
                    Constants.LastModeFlag = false;
                    AlbumMediaSessionManager.get().updatePlaybackState();
                    for (OnAlbumRadioPlayerEventListener listener : listeners) {
                        Observable.just("action").observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
                            @Override
                            public void onCompleted() {

                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onNext(String s) {
                                listener.onPlayerPause();
                            }
                        });
                    }
                }
            } else {
                state = STATE_PLAYING;


                Observable.just("action").observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(String s) {
                        EventBus.getDefault().post(new WaveAction());
                    }
                });


                handler.post(mPublishRunnable);
                AlbumMediaSessionManager.get().updatePlaybackState();
                mediaPlayer.start();
                PreferenceUtils.SaveRadioPlayingStatus(true);
                for (OnAlbumRadioPlayerEventListener listener : listeners) {
                    Observable.just("action").observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onNext(String s) {
                            listener.onPlayerStart();
                        }
                    });
                }
            }
        }
    }

    public void pausePlayer() {
        pausePlayer(false);
    }

    public void pausePlayer(boolean abandonAudioFocus) {
//        if (!isPlaying()) {
//            return;
//        }
        Logger.i("radio pausePlayer()");
        mediaPlayer.pause();
        PreferenceUtils.SaveRadioPlayingStatus(false);
        state = STATE_PAUSE;

        Observable.just("action").observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(String s) {
                EventBus.getDefault().post(new WaveAction());
            }
        });


        EventBus.getDefault().post(new WaveAction());
        if (mPublishRunnable != null) {
            handler.removeCallbacks(mPublishRunnable);
        }
//        Notifier.get().showPause(getPlayMusic());
        AlbumMediaSessionManager.get().updatePlaybackState();
//        context.unregisterReceiver(noisyReceiver);
        Constants.FLAG_PAUSE_MANUAL = abandonAudioFocus;

        if (abandonAudioFocus) {
//            audioFocusManager.abandonAudioFocus();
            PreferenceUtils.SaveAudioFocusStatus(false);
        }
        PreferenceUtils.SaveRadioPlayingStatus(false);
        for (OnAlbumRadioPlayerEventListener listener : listeners) {


            Observable.just("action").observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onNext(String s) {
                    listener.onPlayerPause();
                }
            });


        }
    }

    public void stopPlayer() {
        if (isIdle()) {
            return;
        }
        Logger.i("radio stopPlayer()");
        pausePlayer();
        mediaPlayer.reset();
        state = STATE_IDLE;
        EventBus.getDefault().post(new WaveAction());
    }


    public boolean getIsPlaying() {
        if (state == STATE_PLAYING) {
            return true;
        }
        return false;
    }

    public void next() {
        if (source == null) {
            return;
        }
        if (source.isIs_paid()) {
            audioFocusManager.getAudioFocusManager().setParameters("jpcc.music=unmute");
            Track track = null;
            for (int index = 0; index < tracks.size(); index++) {
                if (tracks.get(index).getId() == source.getTrackId() && (tracks.get(index).getSubordinatedAlbum().getId() == source.getAlbumId())) {
                    if ((index + 1 < tracks.size())) {
                        Track local_track = tracks.get(index + 1);
                        track = local_track;
                        int from = source.getFrom();
                        source = Track2RecentAlbumTrackUtils.Track2RecentBean(local_track);
                        source.setFrom(from);
                        currentDuration = 0;
//                        play();
                        radioPosition = radioPosition + 1;
                        playUrlForPaied = "";
                        setOnSources(getTracks(), index + 1, from, 0);
                        break;
                    } else {
                        RecentAlbumRadioTrackBean local_recent = this.source;
                        for (OnAlbumRadioPlayerEventListener listener : listeners) {
                            Observable.just("action").observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
                                @Override
                                public void onCompleted() {

                                }

                                @Override
                                public void onError(Throwable e) {

                                }

                                @Override
                                public void onNext(String s) {
                                    listener.onPlayAlbumFinished(local_recent);
                                }
                            });
                        }
                        break;
                    }
                }
            }
        } else {
            audioFocusManager.getAudioFocusManager().setParameters("jpcc.music=unmute");
            for (int index = 0; index < tracks.size(); index++) {
                if (tracks.get(index).getId() == source.getTrackId() && (tracks.get(index).getSubordinatedAlbum().getId() == source.getAlbumId())) {
                    if ((index + 1 < tracks.size())) {
                        Track local_track = tracks.get(index + 1);
                        int from = source.getFrom();
                        source = Track2RecentAlbumTrackUtils.Track2RecentBean(local_track);
                        source.setFrom(from);
                        currentDuration = 0;
                        play();
                        if(mPublishRunnable!=null){
                            handler.removeCallbacks(mPublishRunnable);
                        }
                        handler.post(mPublishRunnable);
                        radioPosition = radioPosition + 1;
                    } else {
                        RecentAlbumRadioTrackBean local_recent = this.source;
                        for (OnAlbumRadioPlayerEventListener listener : listeners) {
                            Observable.just("action").observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
                                @Override
                                public void onCompleted() {

                                }

                                @Override
                                public void onError(Throwable e) {

                                }

                                @Override
                                public void onNext(String s) {
                                    listener.onPlayAlbumFinished(local_recent);
                                }
                            });
                        }
                    }
                    break;
                }
            }
        }
    }

    public void prev() {
        if (source == null) {
            return;
        }
        audioFocusManager.getAudioFocusManager().setParameters("jpcc.music=unmute");
        if("album".equals(source.getType())){
            if (currentDuration > 3000) {
                seekTo(0);
                return;
            }
        }
        if (source.isIs_paid()) {
            for (int index = 0; index < tracks.size(); index++) {
                if (tracks.get(index).getId() == source.getTrackId() && (tracks.get(index).getSubordinatedAlbum().getId() == source.getAlbumId())) {
                    if (index >= 1) {
                        Track local_track = tracks.get(index - 1);
                        int from = source.getFrom();
                        source = Track2RecentAlbumTrackUtils.Track2RecentBean(local_track);
                        source.setFrom(from);
                        currentDuration = 0;
                        radioPosition = radioPosition - 1;
                        playUrlForPaied = "";
//                        pausePlayer();
                        setOnSources(getTracks(), index - 1, from, 0);
//                        play();
                    } else {
                        for (OnAlbumRadioPlayerEventListener listener : listeners) {

                            Observable.just("action").observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
                                @Override
                                public void onCompleted() {

                                }

                                @Override
                                public void onError(Throwable e) {

                                }

                                @Override
                                public void onNext(String s) {
                                    listener.onToPrevAlbum(source);
                                }
                            });


                        }
                    }
                    break;
                }
            }
        } else {
            for (int index = 0; index < tracks.size(); index++) {
                if (tracks.get(index).getId() == source.getTrackId() && (tracks.get(index).getSubordinatedAlbum().getId() == source.getAlbumId())) {
                    if (index >= 1) {
                        Track local_track = tracks.get(index - 1);
                        int from = source.getFrom();
                        source = Track2RecentAlbumTrackUtils.Track2RecentBean(local_track);
                        source.setFrom(from);
                        currentDuration = 0;
                        radioPosition = radioPosition - 1;
                        play();
                    } else {
                        for (OnAlbumRadioPlayerEventListener listener : listeners) {

                            Observable.just("action").observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
                                @Override
                                public void onCompleted() {

                                }

                                @Override
                                public void onError(Throwable e) {

                                }

                                @Override
                                public void onNext(String s) {
                                    listener.onToPrevAlbum(source);
                                }
                            });


                        }
                    }
                    break;
                }
            }
        }
    }


    public void setUnmute() {
        audioFocusManager.getAudioFocusManager().setParameters("jpcc.music=unmute");
    }

    /**
     * 跳转到指定的时间位置
     *
     * @param msec 时间
     */
    public void seekTo(int msec) {
        audioFocusManager.getAudioFocusManager().setParameters("jpcc.music=unmute");
        if (isPlaying() || isPausing() || isPreparing()) {
            mediaPlayer.seekTo(msec);
            currentDuration = msec;
//            if (isPreparing()) {
//            } else if (isPlaying()) {
//            } else if (isPausing()) {
//                startPlayer();
//            } else {
//                play();
//            }
            AlbumMediaSessionManager.get().updatePlaybackState();
            for (OnAlbumRadioPlayerEventListener listener : listeners) {

                Observable.just("action").observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(String s) {
                        listener.onPublish((int) mediaPlayer.getCurrentPosition(), source);
                    }
                });


            }
        }
    }


//    private int localDuration = 0;
//    private boolean flag=false;
//    public void fastForward(int millionSeconds) {
//        if(localDuration==0){
//            localDuration=currentDuration;
//        }
//        flag=true;
//        if (millionSeconds <= 1000 && millionSeconds >= 0) {
//            for (OnAlbumRadioPlayerEventListener listener : listeners) {
//                Observable.just("action").observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
//                    @Override
//                    public void onCompleted() {
//
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//
//                    }
//
//                    @Override
//                    public void onNext(String s) {
//                        listener.onPublish(localDuration+4*millionSeconds, source);
//                    }
//                });
//            }
//        }
//        else if(millionSeconds>1000&&millionSeconds<=4000){
//            for (OnAlbumRadioPlayerEventListener listener : listeners) {
//                Observable.just("action").observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
//                    @Override
//                    public void onCompleted() {
//
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//
//                    }
//
//                    @Override
//                    public void onNext(String s) {
//                        listener.onPublish(localDuration+4000+8*millionSeconds, source);
//                    }
//                });
//            }
//        }
//        else if(millionSeconds>4000&&millionSeconds<=8000){
//            for (OnAlbumRadioPlayerEventListener listener : listeners) {
//                Observable.just("action").observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
//                    @Override
//                    public void onCompleted() {
//
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//
//                    }
//
//                    @Override
//                    public void onNext(String s) {
//                        listener.onPublish(localDuration+4000+24000+16*millionSeconds, source);
//                    }
//                });
//            }
//        }
//        else if(millionSeconds>8000){
//            for (OnAlbumRadioPlayerEventListener listener : listeners) {
//                Observable.just("action").observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
//                    @Override
//                    public void onCompleted() {
//
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//
//                    }
//
//                    @Override
//                    public void onNext(String s) {
//                        listener.onPublish(localDuration+4000+24000+64000+32*millionSeconds, source);
//                    }
//                });
//            }
//        }
//    }

    public void fastForward() {
        if (source != null) {
            if (currentDuration + 20000 < source.getDuration()) {
                currentDuration = currentDuration + 20000;
                if (isPlaying() || isPausing() || isPreparing()) {
                    mediaPlayer.seekTo(currentDuration);
                    AlbumMediaSessionManager.get().updatePlaybackState();
                    for (OnAlbumRadioPlayerEventListener listener : listeners) {

                        Observable.just("action").observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
                            @Override
                            public void onCompleted() {

                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onNext(String s) {
                                listener.onPublish((int) currentDuration, source);
                            }
                        });


                    }
                }
            } else {
                next();
            }
        }
    }


    public void fastBack() {
        if (source != null) {
            if (currentDuration - 20000 > 0) {
                currentDuration = currentDuration - 20000;
                if (isPlaying() || isPausing() || isPreparing()) {
                    mediaPlayer.seekTo(currentDuration);
                    AlbumMediaSessionManager.get().updatePlaybackState();
                    for (OnAlbumRadioPlayerEventListener listener : listeners) {

                        Observable.just("action").observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
                            @Override
                            public void onCompleted() {

                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onNext(String s) {
                                listener.onPublish((int) currentDuration, source);
                            }
                        });


                    }
                }
            } else {
//                prev();
                currentDuration = 0;
                mediaPlayer.seekTo(currentDuration);
            }
        }
    }


    public void seek(int msec) {
        if (isPlaying() || isPausing() || isPreparing()) {
            Message msg = Message.obtain();
            msg.what = msec;
//            delayHandler.sendMessageDelayed(msg, 2000);
//            mediaPlayer.seekTo(msec);
//            AlbumMediaSessionManager.get().updatePlaybackState();
//            for (OnAlbumRadioPlayerEventListener listener : listeners) {
//                listener.onPublish(mediaPlayer.getCurrentPosition(), source);
//            }
        }
    }


//    private Handler delayHandler = new Handler() {
//        @Override
//        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
//            mediaPlayer.seekTo(msg.what);
//            currentDuration=msg.what;
//            AlbumMediaSessionManager.get().updatePlaybackState();
//            for (OnAlbumRadioPlayerEventListener listener : listeners) {
//
//
//                Observable.just("action").observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
//                    @Override
//                    public void onCompleted() {
//
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//
//                    }
//
//                    @Override
//                    public void onNext(String s) {
//                        listener.onPublish(msg.what, source);
//                    }
//                });
//
//
//            }
//        }
//    };

    private Runnable mPublishRunnable = new Runnable() {
        @Override
        public void run() {
            if (Constants.isRelease) {
                if (isPlaying() && source.isLive()) {
                    PreferenceUtils.SaveFrontStatus();
                }
            }

            if (onPublishFlag) {
                if (isPlaying() && !source.isLive()) {
                    for (OnAlbumRadioPlayerEventListener listener : listeners) {


                        Observable.just("action").observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
                            @Override
                            public void onCompleted() {

                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onNext(String s) {
                                if (mediaPlayer.getCurrentPosition() >= source.getDuration()) {
                                    currentDuration=0;
                                    next();
                                } else {
                                    currentDuration=(int) mediaPlayer.getCurrentPosition();
                                    listener.onPublish((int) mediaPlayer.getCurrentPosition(), source);
                                }
                            }
                        });


                    }
                }
            }
            handler.postDelayed(this, TIME_UPDATE);
        }
    };

    public int getAudioSessionId() {
        return mediaPlayer.getAudioSessionId();
    }

    public long getAudioPosition() {
        if (isPlaying() || isPausing()) {
            return mediaPlayer.getCurrentPosition();
        } else {
            return 0;
        }
    }

    public RecentAlbumRadioTrackBean getPlayMusic() {
//        if (musicList.isEmpty()) {
//            return null;
//        }
//        return musicList.get(getPlayPosition());
        if (source == null) {
            return null;
        }
        return source;
    }

    public ExoMediaPlayer getMediaPlayer() {
        return mediaPlayer;
    }

//    public List<Music> getMusicList() {
//        return musicList;
//    }

    public boolean isPlaying() {
        return state == STATE_PLAYING;
    }

    public boolean isPausing() {
        return state == STATE_PAUSE;
    }

    public boolean isPreparing() {
        return state == STATE_PREPARING;
    }

    public boolean isIdle() {
        return state == STATE_IDLE;
    }

//    public int getPlayPosition() {
//        int position = Preferences.getPlayPosition();
//        if (position < 0 || position >= musicList.size()) {
//            position = 0;
//            Preferences.savePlayPosition(position);
//        }
//        return position;
//    }

    private void setPlayPosition(int position) {
//        PreferenceUtils.savePlayPosition(position);
    }


    public void setSourceFrom(int from) {
        if (source != null) {
            source.setFrom(from);
        }
    }

    public void clearBuffering() {
        for (OnAlbumRadioPlayerEventListener listener : listeners) {
            Observable.just("action").observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onNext(String s) {
                    if ("album".equals(source.getType())) {
                        listener.onBufferingUpdate(0);
                    }
                }
            });
        }
    }

    public int getState() {
        return state;
    }

    public int getRadioPosition() {
        return radioPosition;
    }


    public void resetAlbumRadioPlayer() {
        source = null;
        for (OnAlbumRadioPlayerEventListener listener : listeners) {
            Observable.just("action").observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onNext(String s) {
                    listener.onPublish(0, source);
                    listener.onBufferingUpdate(0);
                    listener.onChange(null);
                }
            });
        }


    }


    public void resumePlay() {
//        radioPosition
//                tracks


        if (source == null) {
            return;
        }
        if ("album".equals(source.getType())) {
            setOnSources(tracks, radioPosition, source.getFrom(), currentDuration);
        } else {
            setOnSourcesForRadio(tracks, tracks.get(tracks.size() - 1), source.isLive(), radioPosition);
        }

    }


    public void setMate(int speed) {
        if (mediaPlayer != null) {
//            mediaPlayer.
            mediaPlayer.setRate(speed);
        }
    }

    private boolean onPublishFlag = true;

    public void setOnpublishFlag(boolean flag) {
        onPublishFlag = flag;
    }


//    public void setSource(RecentAlbumRadioTrackBean sou) {
//        this.source = sou;
//        play();
//    }
}
